package ro.isdc.training.jpa.systemuser.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ro.isdc.training.jpa.systemuser.dao.SystemUserDAO;
import ro.isdc.training.jpa.systemuser.domain.SystemUser;
import ro.isdc.training.jpa.systemuser.domain.SystemUserId;

/**
 * System User Data Access Object Implementation
 * 
 * All method will be REQUIRED using Spring Transactions due to the @Transactional
 * annotation on the class.
 * 
 * @author Andrei Chirila
 */
public class SystemUserDAOImpl implements SystemUserDAO {

	@PersistenceContext
	private EntityManager entityManager;
	
	public SystemUser findSystemUserByIdentification(final SystemUserId systemUserId) {
		List<Object> paramValuesList = new ArrayList<Object>();
    List<String> paramNamesList = new ArrayList<String>();
    
    String sql ="select su from SystemUser su";
    if (systemUserId != null) {
    	if (systemUserId.getEntityId() > 0) {
    		sql += " where su.entityId = :entityId";
    		paramNamesList.add("entityId");
    		paramValuesList.add(systemUserId.getEntityId());
    	} else {
    		sql += " where su.username = :username";
    		paramNamesList.add("username");
    		paramValuesList.add(systemUserId.getUsername());
    	}
    }
   
    return 	(SystemUser) entityManager.createQuery(sql).setParameter(paramNamesList.get(0), paramValuesList.get(0)).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	public List<SystemUser> findSystemUsers() {
		return entityManager.createNativeQuery("select * from System_Users",
				SystemUser.class).getResultList();
	}

	public Serializable save(SystemUser systemUser) {
		entityManager.persist(systemUser);
		return systemUser.getEntityId();
	}

	public SystemUser update(SystemUser systemUser) {
		entityManager.merge(systemUser);
		return systemUser;
	}

}
